#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <getopt.h>
#include <regex.h>

#include <curl/curl.h>

#include "../error.h"
#include "../main.h"
#include "../util.h"
#include "logout.h"
#include "../action/logout.h"

_Noreturn void verb_logout_usage(FILE *restrict out) {
    fputs("Usage: " PROGRAM_NAME " logout [USER INDEX]\n", out);
    fputs("Log out the network.\n", out);
    fputs("Portal host is required.\n", out);
    fputs("\n", out);
    fputs("Options:\n", out);
    fputs("  -h, --help                 display this help and exit\n", out);
    fputs("\n", out);
    fputs("Exit status:\n", out);
    fputs(" 0  if logout successfully\n", out);
    fputs(" 1  if logout failed\n", out);
    fputs(" 2  if unable to parse JSON\n", out);
    fputs(" 3  if unable to connect to the logout interface\n", out);
    exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}

int verb_logout(const int argc, char* const* argv) {
    int lose = 0;
    static struct option long_options[] = {
        {"help",      no_argument,        NULL, 'h' },
        {0,           0,                  0,     0 }
    };
    const char* user_index = NULL;
    
    while (1) {
        int c = getopt_long(argc, argv, "-h", long_options, NULL);

        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                verb_logout_usage(stdout);
                break;

            case 1:
                if (user_index != NULL) {
                    error(0, 0, "exceed argument: %s", optarg);
                    verb_logout_usage(stderr);
                }
                user_index = optarg;
                break;

            default:
                lose = 1;
                break;
        }
    }

    if (lose) {
        verb_logout_usage(stderr);
        return EXIT_FAILURE;
    }
    
    if (GLOBAL_ARGS.portal_host == NULL) {
        error(0, 0, "No host provided.");
        exit(EXIT_FAILURE);
    }
    
    action_logout_result result = action_logout(
        GLOBAL_ARGS.bind_interface,
        GLOBAL_ARGS.portal_host,
        GLOBAL_ARGS.portal_search,
        user_index
    );
    
    switch (result.status) {
        case ACTION_LOGOUT_SUCCESSFULLY:
            puts("Status: succeed");
            return 0;
        case ACTION_LOGOUT_FAILED:
            puts("Status: failed");
            printf("Message: %s\n", result.message);
            return 1;
        case ACTION_LOGOUT_PARSING_FAILED:
            return 2;
        case ACTION_FETCHING_FAILED:
            return 3;
        default:
            assert(0);
            exit(1);
            break;
    }
}
